﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.XPath;
using System.Text;
using System.IO;
using System.Globalization;
using SpLocalizer.Common;
using SpLocalizer.Common.DbApi;
using CDO;
using ADODB;

namespace SpLocalizer.ContentSourceProviders.Eml
{
    public class EmlFileContent : SpLocalizer.ContentSourceProviders.XPath.XPathContent
    {

        private CDO.Message msg = null;
        protected string TaskLanguage = String.Empty;


        public EmlFileContent() : base(null) { }

        public override void Bind(string EmlFilePath)
        {
            this.ContentAddress = EmlFilePath;
            this.msg = new CDO.MessageClass();          
            ADODB.Stream stream = new ADODB.StreamClass();
            
            stream.Charset = "utf-8";
            stream.Type = StreamTypeEnum.adTypeText;
            stream.Open(Type.Missing, ADODB.ConnectModeEnum.adModeUnknown, ADODB.StreamOpenOptionsEnum.adOpenStreamUnspecified, String.Empty, String.Empty);
            stream.LoadFromFile(EmlFilePath);
            stream.Flush();
            msg.DataSource.OpenObject(stream, "_Stream");

            stream.Close();
        }

        public override IEnumerable<BaseTranslationTask> BuildTranslationTasks(CultureInfo FromLanguage, CultureInfo ToLanguage)
        {
            // Select all book nodes that have the matching attribute value.
            List<BaseTranslationTask> tasksToTranslate = new List<BaseTranslationTask>();

            if (this.msg == null)            
                return tasksToTranslate;

            if (msg.Subject != null && !string.IsNullOrEmpty(msg.Subject) && !string.IsNullOrEmpty(msg.Subject.Trim()))
            {
                tasksToTranslate.Add(new EmlContentLocalizationTask(FromLanguage, ToLanguage,
                                        EmlContentLocalizationTask.Attr_Subject, msg.Subject));
            }

            if (msg.HTMLBody != null && !string.IsNullOrEmpty(msg.HTMLBody) && !string.IsNullOrEmpty(msg.HTMLBody.Trim()))
            {
                EmlContentLocalizationTask body = new EmlContentLocalizationTask(FromLanguage, ToLanguage,
                                        EmlContentLocalizationTask.Attr_Body, msg.HTMLBody);
                body.Format = Constants.TASK_FORMAT_HTML;
                tasksToTranslate.Add(body);

            }

            return tasksToTranslate;
        }

        public override void ExportContentTranslations(BaseTranslationTask TranslationTask)
        {
            TaskLanguage = TranslationTask.ToLanguage.Name; // Set language name from tasks

            string ContentType = msg.Fields["urn:schemas:mailheader:content-type"].Value as string;

            msg.Fields["urn:schemas:mailheader:content-type"].Value = ContentType.Split(';')[0] + "; charset=\"utf-8\"";         
            msg.Fields.Update();
            
            if (EmlContentLocalizationTask.Attr_Subject.Equals(((EmlContentLocalizationTask)TranslationTask).AttributeName))
            {
                msg.Subject = ((EmlContentLocalizationTask)TranslationTask).TranslatedText;
            }
            if (EmlContentLocalizationTask.Attr_Body.Equals(((EmlContentLocalizationTask)TranslationTask).AttributeName))
            {
                msg.HTMLBody = ((EmlContentLocalizationTask)TranslationTask).TranslatedText;
            }
        }

        public override void PerformExportDone()
        {
            ADODB.Stream streamOut = new ADODB.StreamClass();
            streamOut.Charset = "Unicode";
            streamOut.Type = StreamTypeEnum.adTypeText;
            streamOut.Open(Type.Missing, ADODB.ConnectModeEnum.adModeUnknown, ADODB.StreamOpenOptionsEnum.adOpenStreamUnspecified, String.Empty, String.Empty);
            msg.DataSource.SaveToObject(streamOut, "_Stream");

            string fileContents = msg.GetStream().ReadText(msg.GetStream().Size);
            streamOut.Close();

            if (string.IsNullOrEmpty(this.TaskLanguage))
                return;

            FileInfo fi = new FileInfo(this.ContentAddress);
            DirectoryInfo dir = fi.Directory; //.CreateSubdirectory(this.TaskLanguage);

            File.WriteAllText(fi.FullName, fileContents);
            //streamOut.SaveToFile(dir.FullName + "\\" + fi.Name, SaveOptionsEnum.adSaveCreateOverWrite);
            
        }
    }
}
